﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wq.Extensions;
using Wq.Extensions.Common;
using Wq.ManagerService;
using Wq.ManagerService.Entities;
using Wq.ManagerService.Models;
using Wq.Model;


namespace Wq.Application
{
    public class FileApplication : BaseApplication
    {
        private readonly OssFileService ossFileService;
        private readonly CategoryService categoryService;
        public FileApplication(OssFileService ossFileService, CategoryService categoryService)
        {
            this.ossFileService = ossFileService;
            this.categoryService = categoryService;
        }


        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="pageModel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public MessageModel List(PageModel<FileQuery> pageModel)
        {
            int count = 0;
            return new MessageModel { Data = ossFileService.List(pageModel, ref  count), Count = count}; 
        }

        /// <summary>
        /// 图片库 
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public string  UploadImage(UploadImageCommand command)
        {
            var fileName = command.File.FileName;
            if (!AllowExtensionByImage(fileName))
                throw new MyException("不支持的文件格式");
            string extension = Path.GetExtension(fileName).ToLower();
            var ossPath = OssManagement.File_Image(Guid.NewGuid().ToString("N"), extension);
            var stream = command.File.OpenReadStream();

            if (stream.Length > 0x300000)//3M
                throw new MyException("文件大小不能超过3M");

            var eTag = AliyunOSSHelper.PutObject(ossPath, stream);
            var editor = new FileEditor()
            {
                CategoryId = command.Category,
                Name = command.File.FileName,
                Type = FileType.Image,
                Size = stream.Length,
                ETag = eTag,
                SupplierId = 0,
                Path = ossPath
            };
            ossFileService.Create(editor);
            return ossPath;
        }

        /// <summary>
        /// 是否为可用文件扩展名
        /// </summary>
        public bool AllowExtensionByImage(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLower();
            var allow = ".jpg|.gif|.png|.bmp|.jpeg|.webp|.jfif";
            return allow.Contains(extension);
        }

        /// <summary>
        /// 上传视频
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public MessageModel UploadVideo(UploadVideoCommand command)
        {
            if (command.Video == null)
                throw new MyException("请选择上传视频文件");
            var videoStream = command.Video?.OpenReadStream();
            var videoFileName = command.Video?.FileName;

            if (!AllowExtensionByVideo(videoFileName))
                throw new MyException("不支持的视频文件格式");

            var size = videoStream.Length / 1024 / 1024;
            if (size > 30)
                throw new MyException("视频大小不能超过30M");

            string videoExtension = Path.GetExtension(videoFileName).ToLower();
            var videoOssPath = OssManagement.File_Video(Guid.NewGuid().ToString("N"), videoExtension);
            var eTag = AliyunOSSHelper.PutObject(videoOssPath, videoStream);

            string coverOssPath = string.Empty;
            if (command.Cover != null) {
                var coverStream = command.Cover?.OpenReadStream();
                var coverFileName = command.Cover?.FileName;
                if (!AllowExtensionByImage(coverFileName))
                    throw new MyException("]不支持的封面文件格式");
                if (coverStream.Length > 0x300000)//3M
                    throw new MyException("文件大小不能超过3M");
                string coverExtension = Path.GetExtension(coverFileName).ToLower();
                coverOssPath = OssManagement.File_Image(Guid.NewGuid().ToString("N"), coverExtension);
                AliyunOSSHelper.PutObject(coverOssPath, coverStream);
            }
            var editor = new FileEditor()
            {
                CategoryId = command.Category,
                Name = videoFileName,
                Type = FileType.Video,
                Size = videoStream.Length,
                ETag = eTag,
                SupplierId = 0,
                Path = videoOssPath,
                Cover = coverOssPath
            };
            ossFileService.Create(editor);
            return new MessageModel { Data = new { Video = videoOssPath, Cover = coverOssPath }};
        }

        /// <summary>
        /// 允许的文件扩展名
        /// </summary>
        public bool AllowExtensionByVideo(string fileName)
        {
            var extension = Path.GetExtension(fileName);
            var allow = ".mp4|.3gp";
            return allow.Contains(extension);
        }

        /// <summary>
        /// 修改文件名称
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        public void SetImageName(long id, string name) => ossFileService.SetName(id, name);
       
        /// <summary>
        /// 批量分组
        /// </summary>
        /// <param name="edior"></param>
        public void SetGroup(BatchEdior edior) => ossFileService.SetGroup(edior);
        

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="id"></param>
        public void RemoveImage(BatchEdior edior) => ossFileService.Remove(edior);

        #region 分类
        public List<CategoryEditor> CategoryList(FileType type) => categoryService.List(type);


        /// <summary>
        /// 文件分类
        /// </summary>
        /// <param name="editor"></param>
        /// <returns></returns>
        public void CategorySave(CategoryEditor category)
        {
            Verify(category);
            if (category.Id > 0)
                categoryService.Save(category);
            else
            {
                var info = categoryService.GetById(category.Id);
                var mode = category.Map<CategoryInfo>();
                if (info != null)
                    mode.FileCount = info.FileCount + 1;
                categoryService.Insert(mode);
                categoryService.RemoveCache(category.Type);
            }
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="editor"></param>
        private void Verify(CategoryEditor editor)
        {
            if (string.IsNullOrWhiteSpace(editor.Name))
                throw new MyException("分类名称不能为空");
            if (categoryService.Count(p => p.Name == editor.Name && p.Type == (int)editor.Type) > 0)
                throw new MyException("已经存在了相同名称的分类");
        }

        /// <summary>
        /// 修改文件分类名称
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        public void SetCategoryName(long id, string name)=> categoryService.SetName(id, name);
       

        /// <summary>
        /// 删除文件分类
        /// </summary>
        /// <param name="id"></param>
        public void RemoveCategory(long id) => categoryService.Remove(id);
       
        #endregion

    }
}
